package ua.com.fesvlast.hotel.model.commands;

import java.io.IOException;




import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;





import ua.com.fesvlast.hotel.controller.managers.ConfigurationManager;
import ua.com.fesvlast.hotel.controller.managers.MessageManager;
import ua.com.fesvlast.hotel.model.dao.DAOFactory;
import ua.com.fesvlast.hotel.model.enteties.Users;


public class LoginCommand implements ICommand {
	
	
	@Override
	public String execute(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
			
		String page =null;
		String login =request.getParameter("login");
		String password=request.getParameter("password");
		boolean save_log_and_pass=Boolean.valueOf(request.getParameter("save_log"));
		Users currentUser =null;
		String luid=null;
		String puid=null;
		Cookie[] MyCookies =request.getCookies();

		if(MyCookies !=null && login==null && password==null){
				for (Cookie c : MyCookies)
				{
					if (c.getName().equalsIgnoreCase("luid"))
					{
						//set the uid from cookie value
						luid = c.getValue();
					}
					else if (c.getName().equalsIgnoreCase("puid"))
					{
						//set the pwd from cookie value
						 puid = c.getValue();
					}
			}	
			currentUser =DAOFactory.getUsersDAO().getUser(luid, puid);
			if(currentUser!=null){
				HttpSession session =request.getSession();
				session.setAttribute("currentUser", currentUser);
				page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.MAIN_PAGE_PATH);
				return page;
			}
		}
		
		currentUser =DAOFactory.getUsersDAO().getUser(login, password);
		
		if(currentUser !=null){
			
			HttpSession session =request.getSession();
			session.setAttribute("currentUser", currentUser);
			page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.MAIN_PAGE_PATH);
			Cookie cookieL=null;
			Cookie cookieP=null;
			MyCookies=null;
			
			if(save_log_and_pass){
				cookieL = new Cookie("luid", login);
				cookieP = new Cookie("puid", password);
				cookieL.setMaxAge(60*60*24);
				cookieP.setMaxAge(60*60*24);
				response.addCookie(cookieL);
				response.addCookie(cookieP);
			}else{
				//MyCookies=null;
				cookieL = new Cookie("luid", "");
				cookieP = new Cookie("puid", "");
				cookieL.setMaxAge(0);
				cookieP.setMaxAge(0);
				response.addCookie(cookieL);
				response.addCookie(cookieP);
			}
				
		}else{
			request.setAttribute("errorMessage", MessageManager.getInstance().getProperty(
					MessageManager.LOGIN_ERROR_MESSAGE));
			
			page=ConfigurationManager.getInstance().getProperty(
					ConfigurationManager.ERROR_PAGE_PATH);
		}
		return page;
	}

}
